package edu.citadel.presentation.resolution;

import com.google.gson.Gson;
import net.sourceforge.stripes.action.Resolution;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Type;

/**
 * @author jordan
 */
public class GsonResolution implements Resolution {
    private final Object src;
    private final Type typeOfSrc;
    private final int errorCode;


    public GsonResolution(Object src) {
        this(src, null, 200);
    }

    public GsonResolution(Object src, int errorCode) {
        this(src, null, errorCode);
    }

    public GsonResolution(Object src, Type typeOfSrc) {
        this(src, typeOfSrc, 200);
    }

    public GsonResolution(Object src, Type typeOfSrc, int errorCode) {
        this.src = src;
        this.typeOfSrc = typeOfSrc;
        this.errorCode = errorCode;
    }

    public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/json");
        response.setStatus(errorCode);

        String json;
        Gson gson = new Gson();

        if (typeOfSrc == null) {
            json = gson.toJson(src);
        } else {
            json = gson.toJson(src, typeOfSrc);
        }

        response.getWriter().print(json);
    }
}
